package carcassonne.server.http.controller;

import carcassonne.server.http.HttpContext;
import carcassonne.server.http.HttpParams;
import carcassonne.server.ioc.Controller;
import carcassonne.server.ioc.HttpMessageHandler;
import carcassonne.server.ioc.RequestMapping;
import carcassonne.user.UserInfo;
import carcassonne.user.UserManager;
import org.apache.log4j.Logger;

import java.util.UUID;

import static carcassonne.server.ioc.HttpMessageDispatcher.*;

@Controller
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = Logger.getLogger(UserController.class);

    @HttpMessageHandler(method = Post, path = "/user")
    public void CreateUser(HttpContext context, HttpParams params) {

    }

    @HttpMessageHandler(method = Post, path = "/login", params = "uuid,user_info")
    public void Login(HttpContext context, HttpParams params) {
        if (!params.Has("uuid")) {
            context.ResponseForbidden("empty uuid!");
            return;
        }
        String uuid = params.GetString("uuid");
        UserInfo userInfo = params.GetObject("user_info", UserInfo.class);

        // 昵称是否合法
        if (!userInfo.IsLegalNickname()) {
            context.ResponseForbidden("illegal nickname");
            return;
        }

//        String token = CryptUtils.Base64Format("carcassonne" + userInfo.nickname + uuid);
        String token = UUID.randomUUID().toString();

        // 是否已经登录
        if (!UserManager.GetInstance().IsLoginUser(token)) {
            UserManager.GetInstance().Login(token, userInfo);
        } else {
            UserManager.GetInstance().Update(token, userInfo);
        }

        userInfo.token = token;

        logger.info("user login: <" + userInfo.nickname + ">");
        context.ResponseOK(userInfo);
    }

    @HttpMessageHandler(method = Put, path = "/nickname", params = "token,nickname")
    public void ChangeNickname(HttpContext context, HttpParams params) {

        String token = params.GetString("token");

        UserManager manager = UserManager.GetInstance();

        if (!manager.IsLoginUser(token)) {
            context.ResponseForbidden("not a login user!");
            return;
        }

        String nickname = params.GetString("nickname");
        UserInfo userInfo = manager.UpdateNickname(manager.GetUserID(token), nickname);
        if (userInfo != null) {
            context.ResponseOK(userInfo);
        } else {
            context.ResponseForbidden("can not found user with token " + token);
        }
    }

    @HttpMessageHandler(method = Get, path = "/test", params = "key")
    public void Test(HttpContext context, HttpParams params) {
        context.ResponseOK("中文测试");
    }
}
